package org.esgi.transformer.impl;

import org.esgi.model.impl.Answer;
import org.esgi.model.interfaces.IAnswer;

import org.esgi.transformer.interfaces.IXMLAnswerTransformer;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLAnswerTransformer extends XMLModelTransformer implements IXMLAnswerTransformer
{
	public static final String XMLAnswerNodeName = "answer";
	public static final String XMLAnswerNextAttrName = "next";
	public static final String XMLAnswerContentNodeName = "content";

	@Override
	public IAnswer answerFromElement(Element e) 
	{
		Answer a = new Answer();
		a.setNextQuestionId(e.getAttribute(this.addDefaultNamespaceToName(XMLAnswerNextAttrName)));
		NodeList nl = e.getChildNodes();
		for(int i=0 ; i<nl.getLength(); i++)
		{
			Node childNode = nl.item(i);
			if(childNode.getNodeName().equals(this.addDefaultNamespaceToName(XMLAnswerContentNodeName)))
			{
				Node textNode = childNode.getFirstChild();
				if(textNode != null)
					a.setText(textNode.getNodeValue());
			}
		}
		return a;
	}

	@Override
	public Element answerToElement(IAnswer anAnswer, Document doc)
	{
		if((anAnswer instanceof IAnswer) && doc != null)
		{
			Element answerNode = doc.createElement(this.addDefaultNamespaceToName(XMLAnswerNodeName));
			String next = anAnswer.getNextQuestionId();
			if(next != null)
				answerNode.setAttribute(this.addDefaultNamespaceToName(XMLAnswerNextAttrName), next);
			
			Element contentNode = doc.createElement(this.addDefaultNamespaceToName(XMLAnswerContentNodeName));
			contentNode.appendChild(doc.createTextNode(anAnswer.getText()));
			answerNode.appendChild(contentNode);
			
			return answerNode;
		}
		return null;
	}
}
